<template>
    <div class="new-page">
        <div style="margin: -5px 0px 5px;display: flex;">
            <el-input clearable v-model="searchTitle" placeholder="请输入任务名称" style="width: 300px"></el-input>
            <el-button icon="search" type="primary" @click="searchDataClick" style="margin-left: 10px">搜索</el-button>
        </div>
        <div class="centerContent">

            <div class="selectDate">
                <el-button @click="changeToday">今</el-button>
                <!-- 日期切换 -->
                <el-select v-model="value" style="width: 120px;margin-left: 5px;" @change="ganttChangeDateView">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
<!--                <el-button style="margin-left: 5px;" @click="changeFull"><el-icon class="el-icon-full-screen" /></el-button>-->
            </div>
            <!-- 甘特图 -->
            <div ref="gantt" class="gantt-container" />
        </div>

    </div>
</template>
<script>
    import gantt from "dhtmlx-gantt"; // 引入模块
    import "dhtmlx-gantt/codebase/dhtmlxgantt.css";

    export default {
        name: 'HelloWorld',
        props: {
            msg: String
        },
        data() {
            return {
                searchTitle:'',
                value:'d',
                ganttEvent: {},//销毁事件
                options:[
                    {
                        value: 'y',
                        label: '年'
                    },
                    {
                        value: 'm',
                        label: '月'
                    },
                    {
                        value: 'w',
                        label: '周'
                    },
                    {
                        value: 'd',
                        label: '日'
                    },
                ],
                /**
                 * data=[
                 *   {
                 *     id: 1,//必填
                 *     text: "标题",//必填
                 *     type: "task",// 项目类型 task任务 project项目  milestone里程碑
                 *     start_date: "2023/3/15",
                 *     duration: 5,//任务持续时间
                 *     parent: 11,//存在这个属性说明此数据为子任务数据，父任务id为11
                 *     progress: 0.3,//项目任务滑块的进度
                 *     open: true,//是否展开显示
                 *     ....
                 *   },
                 *   {
                 *     id: 2,
                 *     text: "标题2",
                 *     start_date: "2023/3/15",
                 *     duration: 5,
                 *     progress: 0,
                 *     open: true
                 *     ....
                 *   },
                 * ]
                 * # data中有些数据可以直接被读取，其余数据都可以定义在左侧表格columns数据显示
                 * `甘特可直接读取属性
                 *     type  parent  progress open ...
                 * `
                 * ********************************************************************************
                 * links=[
                 *   {
                 *     id:'111',//数据id
                 *     source:'1'
                 *     target:'2'
                 *     type:'0'
                 *   },//
                 *   {
                 *     id:'222'
                 *     source:'2'
                 *     target:'1'
                 *     type:'1'
                 *   },//数据说明 滑块任务2 的头部 指向滑块任务1的头部
                 * ]
                 * #字段解释
                 * 格式 id:数据id
                 *     source:开始链接的项目id  ----为tasks.data中数据的id
                 *     target:要链接项目的id  ----为tasks.data中数据的id
                 *     type: 0--进行-开始  `尾部链接头部`
                 *           1--开始-开始  `头部链接头部`
                 *           2--进行-进行  `尾部链接尾部`
                 *           3--开始-进行  `头部链接尾部`
                 * 复制代码
                 * */
                tasks: {
                    data: [
                        {
                            id: 1,//必填
                            text: "QL12354",//必填
                            process:"222222",
                            task_name:"任务1",
                            equipment:"机台1",
                            start_date: "2023-5-04 08:00:00",//任务持续时间
                            duration: 10,
                            progress: 0.6,
                            open: true,
                            color:"#f1052a"
                        },
                        {
                            id: 2,
                            text: "WL12345",
                            process:"222222",
                            task_name:"任务2",
                            equipment:"123455",
                            start_date: "2023-5-06 08:00:00",
                            duration: 20,
                            progress: 0.4 ,
                            open: true,
                            color:"#f1052a"
                        },
                        {
                            id: 3,
                            text: "gf123",
                            process:"222222",
                            task_name:"任务3",
                            equipment:"机台3号",
                            start_date: "2023-5-09 08:00:00",
                            duration: 10,
                            progress: 0.4 ,
                            open: true,
                            parent:2,
                            color:"#f1052a"
                        },
                        {
                            id: 4,
                            text: "ER1234",
                            process:"222222",
                            task_name:"任务4",
                            equipment:"机台4号",
                            start_date:new Date("2023-11-27 08:00:00") ,
                            end_date:new Date("2023-11-27 12:00:00"),
                            duration: 10/24,
                            progress: 0.4 ,
                            open: true,
                            color:""
                        },
                        {
                            id: 5,
                            text: "qw12311",
                            process:"222222",
                            task_name:"任务5",
                            equipment:"机台5号",
                            start_date:new Date("2023-11-28 07:00:00") ,
                            duration: 20/24,
                            progress: 0.4 ,
                            open: true,
                            color:""
                        },
                    ],
                    links: [{ id: 1, source: 1, target: 2, type: "0" }],
                },
            };
        },
        mounted() {
            //本地化
            // gantt.i18n.setLocale("cn");
            gantt.locale = {
                date: {
                    month_full: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
                    month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                    day_short: ["日", "一", "二", "三", "四", "五", "六"]
                },
                labels: {
                    dhx_cal_today_button: "今天",
                    day_tab: "日",
                    week_tab: "周",
                    month_tab: "月",
                    new_event: "新建日程",
                    icon_save: "保存",
                    icon_cancel: "关闭",
                    icon_details: "详细",
                    icon_edit: "编辑",
                    icon_delete: "删除",
                    confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
                    confirm_deleting: "是否删除计划?",
                    section_description: "描述:",
                    section_time: "时间范围:",
                    section_type: "类型:",
                    section_text: "计划名称:",
                    section_test: "测试:",
                    section_projectClass: "项目类型:",
                    taskProjectType_0: "项目任务",
                    taskProjectType_1: "普通任务",
                    section_head: "负责人:",
                    section_priority: '优先级:',
                    taskProgress: '任务状态',
                    taskProgress_0: "未开始",
                    taskProgress_1: "进行中",
                    taskProgress_2: "已完成",
                    taskProgress_3: "已延期",
                    taskProgress_4: "搁置中",
                    section_template: 'Details',
                    column_text: "计划名称",
                    column_start_date: "开始时间",
                    column_duration: "持续时间",
                    column_add: "",
                    column_priority: "难度",
                    link: "关联",
                    confirm_link_deleting: "将被删除",
                    link_start: " (开始)",
                    link_end: " (结束)",
                    type_task: "任务",
                    type_project: "项目",
                    type_milestone: "里程碑",
                    minutes: "分钟",
                     hours: "小时",
                    days: "天",
                    weeks: "周",
                    months: "月",
                    years: "年"
                }
            }
            //设置左侧列表
            gantt.config.columns=[
                { name: "text", min_width:200,max_width:220, label:"工单", align: "left",resize: true,  tree: true, editor: { type: 'text', map_to: 'text' } },
                { name: "process", label: "工序", min_width:120,max_width:120, resize: true, align: "left" },
                { name: "task_name", label: "任务名称", min_width:120,max_width:120, resize: true, align: "left" },
                { name: "equipment", label: "设备名称", min_width:120,max_width:120, resize: true, align: "left" },
                { name: "start_date", label: "开始时间", min_width:120,max_width:120, resize: true, align: "left" },
                { name: "end_date", label: "结束时间", min_width:120,max_width:120, resize: true, align: "left" },
            ]
            gantt.config.branch_loading = true; // 启用动态加载
            gantt.config.xml_date = "%Y-%m-%d %H:%i"; //日期格式化
            gantt.config.order_branch = true; //是否按照用户手动的顺序对任务进行排序
            gantt.config.order_branch_free = true;//是否允许自由排序子任务
            gantt.config.autofit = true;//左侧是否自适应
            gantt.config.drag_links = true;//连线
            gantt.config.readonly = true;  //只读
            gantt.config.smart_scales = true;//启用或禁用 Gantt 图的智能比例尺功能
            gantt.config.date_scale = "%m月%d日"; //右侧显示列名

            gantt.config.layout = {//拖拽布局
                css: "gantt_container",
                rows: [
                    {
                        cols: [
                            { view: "grid", id: "grid", scrollX: "scrollHor", scrollY: "scrollVer"},// 定义任务表格的宽度
                            { resizer: true, width: 1 },// 分隔符，用于调整布局
                            { view: "timeline", id: "timeline", scrollX: "scrollHor", scrollY: "scrollVer" },// 时间轴区域
                            { view: "scrollbar", scroll: "y", id: "scrollVer" }// 水平滚动条
                        ]
                    },
                    { view: "scrollbar", scroll: "x", id: "scrollHor", height: 20 }// 垂直滚动条
                ]
            };
            gantt.config.start_on_monday = true;//是否从周一显示起始时间---右侧条形图
            gantt.config.work_time = true;     //显示工作时间
            gantt.config.fit_tasks = false;   //自动调整图表坐标轴区间用于适配task的长度
            // 设置任务日期的显示格式
            gantt.config.date_format = "%Y-%m-%d %H:%i";

            gantt.templates.tooltip_text = function(start, end, task) {
                    var yyyy = start.getFullYear();
                    var mm = (start.getMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1
                    var dd = start.getDate().toString().padStart(2, '0');
                    var hh = start.getHours().toString().padStart(2, '0');
                    var min = start.getMinutes().toString().padStart(2, '0');

                    var yyyy1 = end.getFullYear();
                    var mm1 = (end.getMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1
                    var dd1 = end.getDate().toString().padStart(2, '0');
                    var hh1 = end.getHours().toString().padStart(2, '0');
                    var min1 = end.getMinutes().toString().padStart(2, '0');



                return "工单名称："+task.text
                       +"<br>任务进度："+task.progress*100+"%"
                       +"<br>开始时间："+yyyy + '-' + mm + '-' + dd +' '+ hh +':'+ min
                       +"<br>结束时间："+yyyy1 + '-' + mm1 + '-' + dd1 +' '+ hh1 +':'+ min1; // 使用任务的 tooltip 属性作为 Tooltip 文本
            };

            gantt.plugins({
                click_drag: true,//用于启用或禁用通过单击任务条目并拖动来更改任务的开始和结束日期的功能
                drag_timeline: true,// 拖动图
                marker: true,// 时间标记
                fullscreen: true,// 全屏
                tooltip: true,// 鼠标经过时信息
                undo: true // 允许撤销
            })


            // 初始化
            gantt.init(this.$refs.gantt);


            gantt.config.subscales = [{ unit: 'hour', step: 8, date: '%H:%i' }];//左侧表头时间格式
            //今日线
            this.createTodayLine();
            // 数据解析
            gantt.parse(this.tasks);



        },
        methods:{
            // 搜索判断数据
            hasSubstr(parentId,type){
                let task = gantt.getTask(parentId);
                if(type=='tilte'){
                    if(task.text.toLowerCase().indexOf(this.searchTitle) !== -1)
                        return true;
                }
            },
            //点击按钮搜索
            searchDataClick(){
                if(this.searchTitle){
                    this.ganttEvent.onBeforeTaskDisplay=gantt.attachEvent("onBeforeTaskDisplay", (id)=>{
                        if (this.hasSubstr(id,'tilte') ){ return true;}

                        return false;
                    });
                    gantt.refreshData()
                    gantt.render()
                }else{
                    this.ganttEvent.onBeforeTaskDisplay=gantt.attachEvent("onBeforeTaskDisplay", ()=>{
                        return true
                    })
                    gantt.refreshData()
                    gantt.render()
                }

            },
            // 今日线
            createTodayLine() {
                var dateToStr = gantt.date.date_to_str("%Y年%M%d日");
                var markerId = gantt.addMarker({
                    id: 'markerLine',
                    start_date: new Date(),
                    css: "today",
                    text: "今日",
                    title: dateToStr(new Date())
                });
                gantt.updateMarker(markerId);
            },

            // 定位到今日线
            changeToday() {
                this.$nextTick(() => {
                    let ganTT = document.getElementsByClassName('gantt_marker today')
                    gantt.scrollTo(ganTT[0].offsetLeft-300, null);
                })
            },
            // 切换 年 季 月 周 日视图
            ganttChangeDateView(type) {
                switch (type) {
                    case 'y':
                        gantt.config.scale_unit = "year";
                        gantt.config.step = 1;
                        gantt.config.subscales = null;
                        gantt.config.date_scale = "%Y年";
                        gantt.templates.date_scale = null;
                        break;
                    case 'm':
                        gantt.config.scale_unit = 'month';
                        gantt.config.step = 1;
                        gantt.config.date_scale = "%m月";
                        gantt.templates.date_scale = null;
                        gantt.config.subscales = null;

                        break;
                    case 'w':
                        gantt.config.scale_unit = 'week';
                        gantt.config.step = 1;
                        gantt.config.date_scale = "第%w周";
                        gantt.templates.date_scale = null;
                        gantt.config.subscales = null;
                        break;
                    case 'd':
                        gantt.config.scale_unit = 'day';
                        gantt.config.step = 2;
                        gantt.config.date_scale = "%m月%d日";
                        gantt.templates.date_scale = null;
                        gantt.config.subscales =  [{ unit: 'hour', step: 8, date: '%H:%i' }];

                        break;
                }
                gantt.render();
            },
            // 是否全屏
            changeFull() {
                gantt.ext.fullscreen.toggle();
            },





        },

    };
</script>

<style scoped>
    .gantt-container {
        height: 600px;
    }
    .new-page {
        height: 100%;
        background-color:#FFF;
        padding: 20px;
        border-radius: 4px;
    }
    .ant-layout {
        background: #f8f9f9;
    }
    .ant-layout-header {
        background: #fdffff;
        color: rgb(29, 28, 28);
        border: 1px solid #dee0e0;
    }
    .header {
        position: fixed;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .content {
        background: #fdffff;
        height: 99vh;
    }
    .centerContent {
        position: relative;
        background: #fdffff;
        width: 100%;
        overflow-y: auto;
        justify-content: space-between;
    }
    .selectDate {
        width: 125px;
        position: fixed;
        top: 23px;
        right: 28px;
        z-index: 99;
        display: flex;
        justify-content: space-between;
    }
    ::v-deep .gantt_grid_head_cell {
        text-align: left !important;
        padding-left: 5px;
    }
    ::v-deep .gantt_grid_head_text{
        padding-left: 30px;
    }
    /* 今日线 */
    ::v-deep .gantt_marker.today{
        background: #ffb121;
    }




</style>
